//
//  XFRefreshFooterView.m
//  WorkManager
//
//  Created by ukongm on 17/1/9.
//  Copyright © 2017年 ukongm. All rights reserved.
//

#import "XFRefreshFooterView.h"
#import "XFRefreshConst.h"
#import "XFManager.h"
@implementation XFRefreshFooterView

- (NSInteger)viewStyle{
    return XFRefreshViewStyleFooter;
}

- (void)setStatus:(XFRefreshStatus)status{
    
    [super setStatus:status];
    
    switch (status) {
        case XFRefreshStatusNormal:
        {
            [UIView animateWithDuration:XFRefreshAnimationDuration animations:^{
               
                self.scrollView.contentInset = _scrollViewInitSet;
                
            }];
            break;
        }
        case XFRefreshStatusRefreshing:
        {
            
            [UIView animateWithDuration:XFRefreshAnimationDuration animations:^{
                
                UIEdgeInsets inset = self.scrollView.contentInset;
                CGFloat bottom = self.height + _scrollViewInitSet.bottom;
                CGFloat deltaH = [self contentBreakView];
                if (deltaH < 0) { // 如果内容高度小于view的高度
                    bottom -= deltaH;
                }
                inset.bottom = bottom;
                self.scrollView.contentInset = inset;
                [self.scrollView setContentOffset:CGPointMake(0, (self.scrollView.contentSize.height - self.scrollView.height)  + self.height) animated:NO];
            } completion:^(BOOL finished) {
                
            }];
            break;
        }
        case XFRefreshStatusPulling:
            
            break;
        case XFRefreshStatusWillRefresh:
            
            break;
            
        default:
            break;
    }
    
}

#pragma mark 获得scrollView的内容 超出 view 的高度
- (CGFloat)contentBreakView
{
    //保证用户设置的 内边距是有用的
    CGFloat h = self.scrollView.frame.size.height - _scrollViewInitSet.bottom - _scrollViewInitSet.top;
    return self.scrollView.contentSize.height - h;
}

#pragma mark - 每次改变contentSize的时候的监听

- (void)setScrollView:(UIScrollView *)scrollView{
    
    [self.scrollView removeObserver:self forKeyPath:XFRefreshContentSize];
    [scrollView addObserver:self forKeyPath:XFRefreshContentSize options:NSKeyValueObservingOptionNew context:nil];
    
    [super setScrollView:scrollView];
    
    if (!scrollView) {
        [self.scrollView removeObserver:self forKeyPath:XFRefreshContentSize];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    
    
    if ([keyPath isEqualToString:XFRefreshContentSize]) {
        self.frame = [self frameWithStyle:self.viewStyle andScrollView:self.scrollView];
    }
    
}


@end
